﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DevExpress.XtraCharts;
using StockCommon;
using System.Drawing.Imaging;
using StockCommon.data;
using Utilities;
using StockCommon.data.bid5;
namespace StockImageLib
{
    public class StockImageGenerator
    {

        public enum StockImageStyle : int
        {
            DailyImage = 1,
            WeekImage = 2
        }
        private String _StorePath = @"d:\stockimage\";
        public String storePath
        {
            get
            {
                return _StorePath;
            }
            set
            {
                _StorePath = value;
                Directory.CreateDirectory(_StorePath);
            }
        }

        private int _Days = 200;
        public int Days
        {
            get
            {
                return _Days;
            }
            set
            {
                _Days = value;
            }
        }
        private int _Weeks = 80;
        public int Weeks
        {
            get
            {
                return _Weeks;
            }
            set
            {
                _Weeks = value;
            }

        }

        //--------------------------------------------------

        String currentStorePath = "";
        protected void checkInitChart(ChartControl chart, StockImageStyle style)
        {
            //先createPath
            Directory.CreateDirectory(_StorePath);
            switch (style)
            {
                case StockImageStyle.WeekImage:
                    currentStorePath = _StorePath + @"week\" + _Weeks + @"\";
                    break;
                case StockImageStyle.DailyImage:
                    currentStorePath = _StorePath + @"day\" + _Days + @"\";
                    break;
            }
            Directory.CreateDirectory(currentStorePath);
            FileUtils.DeleteSubFilesOnly(currentStorePath);
        }
        protected void SaveChart(ChartControl chart, String code)
        {
            String name = StockManager.getStockName(code);

            String fileName = currentStorePath + code + "_" + name + ".jpg";
            try
            {
                chart.ExportToImage(fileName, ImageFormat.Jpeg);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Write(e.StackTrace);
            }

        }
        /*******************************************************************************************************
         * 
         * 
         * 
         * ******************************************************************************************************/
        public bool FillDailyIndexVolume(ChartControl chart, string code, int rangeCount)
        {
            bool result = false;

            try
            {
                List<StockDaily> datas = StockDataModule.getDailyIndexAndVolume(code, rangeCount * 2);

                Series indexSeries = chart.Series["指數"];
                Series volumeSeries = chart.Series["成交量"];
                CandleStickSeriesView candleStickSeriesView = (CandleStickSeriesView)indexSeries.View;
                SideBySideBarSeriesView sideBySideBarSeriesView = (SideBySideBarSeriesView)volumeSeries.View;

                indexSeries.Points.Clear();
                volumeSeries.Points.Clear();
                DevExpress.XtraCharts.XYDiagram diagram = (XYDiagram)chart.Diagram;


                //diagram.SecondaryAxesY[0].SetVisibilityInPane(false, diagram.DefaultPane);
                //diagram.SecondaryAxesY[0].SetVisibilityInPane(true, diagram.Panes["volumePane"]);



                int sz = datas.Count;
                if (sz == 0)
                {
                    return false;
                }

                SeriesPoint[] stockIndex = new SeriesPoint[sz];
                SeriesPoint[] stockVolume = new SeriesPoint[sz];

                for (int i = 0; i < sz; i++)
                {
                    StockDaily data = datas[i];
                    if (data.開盤價 == null)
                        continue;

                    DateTime dt = data.日期;
                    stockIndex[i] = new SeriesPoint(dt, new double[] { (double)data.最低價, (double)data.最高價, (double)data.開盤價, (double)data.收盤價 });
                    stockVolume[i] = new SeriesPoint(dt, new double[] { ((double)data.成交股數) / 1000 });
                }
                indexSeries.Points.AddRange(stockIndex);
                volumeSeries.Points.AddRange(stockVolume);

                //-----日期 

                DateTime maxDate = datas[sz - 1].日期;
                int si = sz - rangeCount;
                DateTime minDate = DateTime.Now;
                if (si < 0)
                {
                    minDate = datas[0].日期.AddDays(si);
                }
                else
                {
                    minDate = datas[si].日期;
                }
                diagram.AxisX.Range.Auto = false;
                diagram.AxisX.DateTimeGridAlignment = DevExpress.XtraCharts.DateTimeMeasurementUnit.Day;
                diagram.AxisX.DateTimeMeasureUnit = DevExpress.XtraCharts.DateTimeMeasurementUnit.Day;
                diagram.AxisX.Range.MaxValue = maxDate;
                diagram.AxisX.Range.MinValue = minDate;
                result = true;

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }



            return result;
        }
        protected bool FillWeekIndexVolume(ChartControl chart, String code)
        {
            // clear Chart
            bool result = false;
            try
            {
                Series indexSeries = chart.Series["指數"];
                Series volumeSeries = chart.Series["成交量"];
                CandleStickSeriesView candleStickSeriesView = (CandleStickSeriesView)indexSeries.View;
                SideBySideBarSeriesView sideBySideBarSeriesView = (SideBySideBarSeriesView)volumeSeries.View;

                indexSeries.Points.Clear();
                volumeSeries.Points.Clear();

                //Load Data
                List<WeekIndexAndVolume> datas = StockDataModule.getWeekIndexAndVolume(code);
                int sz = datas.Count;
                if (sz == 0)
                {
                    //有剛上市的股票,剛好還沒有備更新過week,因此就會產生0
                    return false;
                }

                SeriesPoint[] stockIndex = new SeriesPoint[sz];
                SeriesPoint[] stockVolume = new SeriesPoint[sz];
                //		DateTime dateTime = DateTime.Parse(arg, DateTimeFormatInfo.InvariantInfo); 
                DateTime dt = DateTime.Now;
                Dictionary<int, StockDataModule.WeekStartEnd> weekToDay = StockDataModule.getWeekToDay();
                for (int i = 0; i < sz; i++)
                {
                    WeekIndexAndVolume data = datas[i];
                    dt = weekToDay[(int)data.YearWeekKey].startDay;

                    stockIndex[i] = new SeriesPoint(dt, new double[] { (double)data.最低價, (double)data.最高價, (double)data.開盤價, (double)data.收盤價 });
                    stockVolume[i] = new SeriesPoint(dt, new double[] { (double)data.成交股數 });
                }
                indexSeries.Points.AddRange(stockIndex);
                volumeSeries.Points.AddRange(stockVolume);

                DevExpress.XtraCharts.XYDiagram diagram = (XYDiagram)chart.Diagram;


                int w = Weeks;
                int curyk = (int)(datas[sz - 1].YearWeekKey);
                int minyk = StockDataModule.getOffsetYearWeekKey(curyk, -w + 1);
                int maxyk = StockDataModule.getOffsetYearWeekKey(curyk, 1);
                DateTime minDate = weekToDay[minyk].startDay;
                DateTime maxDate = weekToDay[maxyk].startDay;

                diagram.AxisX.Range.Auto = false;

                diagram.AxisX.DateTimeGridAlignment = DevExpress.XtraCharts.DateTimeMeasurementUnit.Week;
                diagram.AxisX.DateTimeMeasureUnit = DevExpress.XtraCharts.DateTimeMeasurementUnit.Week;

                diagram.AxisX.Range.MaxValue = maxDate;
                diagram.AxisX.Range.MinValue = minDate;
                result = true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Write(e.Message);
                System.Diagnostics.Debug.Write(e.StackTrace);
            }
            finally
            {

            }
            return result;
            //Load Time
            //指定Range
            //generate Series

        }

        protected int createStockImage(List<String> codes, ChartControl chart, StockImageStyle style, int count = -1)
        {
            checkInitChart(chart, style);
            int c = 0;

            foreach (String code in codes)
            {
                bool created = false;
                switch (style)
                {
                    case StockImageStyle.DailyImage:
                        created = FillDailyIndexVolume(chart, code, count);
                        break;
                    case StockImageStyle.WeekImage:
                        created = FillWeekIndexVolume(chart, code);
                        break;
                }
                if (created)
                {
                    SaveChart(chart, code);
                    c++;
                }
                System.Diagnostics.Debug.WriteLine("step:" + count + "\t" + code);
            }
            return c;
        }

        public int createStockWeekIndexImages(String code, ChartControl chart, StockImageStyle style)
        {
            List<String> ss = new List<string>();
            ss.Add(code);
            return createStockImage(ss, chart, style);
        }
        public int createStockWeekIndexImages(ChartControl chart, StockImageStyle style)
        {
            List<String> codes = StockManager.getRecentValidStockCodes();
            return createStockImage(codes, chart, style);
        }

        public int createStockDailyImages(ChartControl chart, DateTime date, int count = -1)
        {
            List<String> codes = StockManager.getRecentValidStockCodes();
            return createStockImage(codes, chart, StockImageStyle.DailyImage, count);
        }

        public bool FillStockMinuteDetailImage(ChartControl chart, DateTime date)
        {
            return true;
        }

     

    }
}
